package com.mx.project.services.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.mx.project.common.resp.ApiResult;
import com.mx.project.constants.AliPayConstants;
import com.mx.project.constants.Constants;
import com.mx.project.dao.OrderMapper;
import com.mx.project.pojo.Order;
import com.mx.project.pojo.Product;
import com.mx.project.services.CartService;
import com.mx.project.services.OrderService;
import com.mx.project.services.ProductService;
import com.mx.project.vo.CartInfo;
import com.mx.project.vo.OrderInfo;
import com.sun.org.apache.xpath.internal.operations.Or;
import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CartService cartService;

    @Transactional
    @Override
    public synchronized String aliPay(List<CartInfo> lists, Integer uid) throws AlipayApiException {
        String bh = UUID.randomUUID().toString().replaceAll("-", "");
        //计算金额
        int count = 0;
        List<Order> orders = new ArrayList<>();
        Order order;
        for (int i = 0; i < lists.size(); i++) {
            order = new Order();
            count += lists.get(i).getCount() * lists.get(i).getNprice();
            order.setCreateTime(new Date());
            order.setOnumber(bh);
            order.setPid(lists.get(i).getPid());
            order.setState(0); //0 待支付
            order.setUid(uid);
            orders.add(order);

        }
        //使用事务 创建订单  先创建数据库中 , 等成功后再进行修改数据
        try {
            submitOrder(orders);
        }catch (Exception e){
            log.error("提交订单失败!");
            throw e;
        }
        // 构建支付数据信息
        Map<String, String> data = new HashMap<>();
        data.put("subject", "请进行支付"); //订单标题
        data.put("out_trade_no", bh); //商户订单号,64个字符以内、可包含字母、数字、下划线；需保证在商户端不重复      //此处模拟订单号为时间
        data.put("timeout_express", "1h"); //该笔订单允许的最晚付款时间
        data.put("total_amount", count+""); //订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
        data.put("product_code", "FAST_INSTANT_TRADE_PAY"); //销售产品码，商家和支付宝签约的产品码，为固定值QUICK_MSECURITY_PAY
        //构建客户端
        DefaultAlipayClient alipayRsa2Client = new DefaultAlipayClient(
                AliPayConstants.gatewayUrl,
                AliPayConstants.app_id,
                AliPayConstants.merchant_private_key,
                "json",
                AliPayConstants.charset,
                AliPayConstants.alipay_public_key,
                AliPayConstants.sign_type);
//        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();// APP支付
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 网页支付
//        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();  //移动h5
        request.setNotifyUrl("http://28l680x684.qicp.vip/order/notify");
        request.setReturnUrl("http://mall.tudoublog.com/");
        request.setBizContent(JSON.toJSONString(data));
        String response = null;
        AlipayTradePagePayResponse response1;
        try {
            response = alipayRsa2Client.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            log.error(e.getErrMsg());
            throw e;
        }
        return response;
    }

    @Override
    public void submitOrder(List<Order> orders) {
        orderMapper.insertOrderLists(orders);
    }

    @Override
    public List<OrderInfo> getOrderByUid(Integer uid) {
        return null;
    }

    @Override
    public List<Order> getOrderByOnumber(String onumber) {
        return orderMapper.selectByOnumber(onumber);
    }

    @Override
    public int updateStateByOnumber(String onumber,Integer state) {
        return orderMapper.updateStateByOnumber(onumber,state);
    }
}
